package com.lxw.filesystem.service;

import com.lxw.filesystem.dao.FileSystemRepository;
import com.lxw.framework.domain.filesystem.FileSystem;
import com.lxw.framework.domain.filesystem.response.FileSystemCode;
import com.lxw.framework.domain.filesystem.response.UploadFileResult;
import com.lxw.framework.exception.ExceptionCast;
import com.lxw.framework.model.response.CommonCode;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 *
 */
@Service
@Slf4j
public class FilesystemService {
    @Autowired
    private FileSystemRepository fileSystemRepository;

    @Value("${lxw.fastdfs.tracker_servers}")
    private String tracker_servers;

    @Value("${lxw.fastdfs.charset}")
    private String charset;
    @Value("${lxw.fastdfs.connect_timeout_in_seconds}")
    private Integer connect_timeout_in_seconds;
    @Value("${lxw.fastdfs.network_timeout_in_seconds}")
    private Integer network_timeout_in_seconds;


    public UploadFileResult upload(MultipartFile multipartFile, String businesskey, String filetag, Map metadata) {

        if (multipartFile==null){
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }
        //把文件上传到fastDfs  返回文件id
        String fileId = upload2fastDfs(multipartFile);
        System.out.println(fileId);
        //把文件信息保存到MongoDB数据库中
        FileSystem fileSystem = new FileSystem();
        fileSystem.setBusinesskey(businesskey);
        fileSystem.setFiletag(filetag);
        fileSystem.setMetadata(metadata);
        fileSystem.setFileId(fileId);
        fileSystem.setFilePath(fileId);
        fileSystem.setFileSize(multipartFile.getSize());
        fileSystemRepository.save(fileSystem);
        return new UploadFileResult(CommonCode.SUCCESS,fileSystem);
    }

    private void initFsds(){
        try {
            ClientGlobal.initByTrackers(tracker_servers);
            ClientGlobal.setG_charset(charset);
            ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
            ClientGlobal.setG_network_timeout(network_timeout_in_seconds);
        } catch (IOException e) {
            log.error(e.getMessage());
            e.printStackTrace();
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_SERVERFAIL);
        } catch (MyException e) {
            e.printStackTrace();
        }
    }
    private String upload2fastDfs(MultipartFile multipartFile){
        //初始化fastDfs信息
        initFsds();
        TrackerClient trackerClient = new TrackerClient();
        try {
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storeStorage);
            String originalFilename = multipartFile.getOriginalFilename();
            String exe = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            System.out.println(exe);
            String fileId = storageClient1.upload_file1(multipartFile.getBytes(), exe, null);
            return fileId;
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_SERVERFAIL);
        }
        return null;
    }
}
